import React, { useState, useCallback, useMemo, useEffect } from 'react';
import { Button, Space, Card, message, Modal, Input, ColorPicker, Drawer, Form, InputNumber, Upload, Dropdown, Tooltip, Switch } from 'antd';
import { DeleteOutlined, SaveOutlined, ClearOutlined, EditOutlined, UndoOutlined, RedoOutlined, UploadOutlined, SettingOutlined, CopyOutlined, AppstoreOutlined } from '@ant-design/icons';
import ReactFlow, {
  Background,
  Controls,
  MiniMap,
  useNodesState,
  useEdgesState,
  addEdge,
  Connection,
  Node,
  NodeChange,
  EdgeChange,
  applyNodeChanges,
  applyEdgeChanges,
  Position,
  Edge,
  Handle
} from 'reactflow';
import 'reactflow/dist/style.css';
import './index.scss';

// 流程图节点类型
type NodeType = 'input' | 'output' | 'default';

// 节点数据接口
interface NodeData {
  label: string;
  description?: string;
  color?: string;
  fontSize?: number;
  borderWidth?: number;
  borderColor?: string;
  backgroundColor?: string;
}

// 自定义节点组件
const CustomNode: React.FC<{ data: NodeData; selected: boolean }> = ({ data, selected }) => {
  return (
    <div className="custom-node-wrapper">
      {/* 输入连接点 */}
      <Handle
        type="target"
        position={Position.Left}
        id="left"
        style={{
          background: '#1890ff',
          width: 10,
          height: 10,
          border: '2px solid #fff',
          left: -5
        }}
      />
      
      {/* 上方连接点 */}
      <Handle
        type="target"
        position={Position.Top}
        id="top"
        style={{
          background: '#1890ff',
          width: 10,
          height: 10,
          border: '2px solid #fff',
          top: -5
        }}
      />
      
      {/* 节点内容 */}
      <div 
        className="custom-node"
        style={{
          backgroundColor: data.backgroundColor || '#fff',
          border: `${data.borderWidth || 1}px solid ${data.borderColor || '#ccc'}`,
          borderRadius: '8px',
          padding: '12px 16px',
          fontSize: `${data.fontSize || 14}px`,
          color: data.color || '#333',
          minWidth: '120px',
          textAlign: 'center',
          boxShadow: selected 
            ? '0 0 0 2px #1890ff, 0 4px 12px rgba(24, 144, 255, 0.3)' 
            : '0 2px 8px rgba(0,0,0,0.15)',
          transition: 'all 0.2s ease',
          position: 'relative',
          cursor: 'pointer'
        }}
      >
        <div className="node-label" style={{ fontWeight: 500, lineHeight: 1.4 }}>
          {data.label}
        </div>
        {data.description && (
          <div 
            className="node-description" 
            style={{ 
              fontSize: '12px', 
              opacity: 0.7, 
              marginTop: '6px',
              lineHeight: 1.3,
              wordBreak: 'break-word'
            }}
          >
            {data.description}
          </div>
        )}
      </div>
      
      {/* 输出连接点 */}
      <Handle
        type="source"
        position={Position.Right}
        id="right"
        style={{
          background: '#1890ff',
          width: 10,
          height: 10,
          border: '2px solid #fff',
          right: -5
        }}
      />
      
      {/* 下方连接点 */}
      <Handle
        type="source"
        position={Position.Bottom}
        id="bottom"
        style={{
          background: '#1890ff',
          width: 10,
          height: 10,
          border: '2px solid #fff',
          bottom: -5
        }}
      />
    </div>
  );
};

const FlowChart: React.FC = () => {
  // 定义初始节点和边缘状态
  const [nodes, setNodes] = useNodesState([]);
  const [edges, setEdges] = useEdgesState([]);
  const [selectedNodeType, setSelectedNodeType] = useState<NodeType | null>(null);
  
  // 编辑相关状态
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [editingNode, setEditingNode] = useState<Node | null>(null);
  const [isPropertiesDrawerVisible, setIsPropertiesDrawerVisible] = useState(false);
  const [selectedNodes, setSelectedNodes] = useState<Node[]>([]);
  
  // 历史记录用于撤销重做
  const [history, setHistory] = useState<{ nodes: Node[]; edges: Edge[] }[]>([]);
  const [historyIndex, setHistoryIndex] = useState(-1);
  const [isSnapToGrid, setIsSnapToGrid] = useState(true);
  const [gridSize] = useState(15);
  
  // 表单实例
  const [form] = Form.useForm();
  const [propertiesForm] = Form.useForm();

  // 自定义节点类型
  const nodeTypes = useMemo(() => ({
    custom: CustomNode
  }), []);

  // 保存历史状态
  const saveToHistory = useCallback((newNodes: Node[], newEdges: Edge[]) => {
    const newHistory = history.slice(0, historyIndex + 1);
    newHistory.push({ nodes: newNodes, edges: newEdges });
    setHistory(newHistory);
    setHistoryIndex(newHistory.length - 1);
    
    // 限制历史记录数量
    if (newHistory.length > 50) {
      const trimmedHistory = newHistory.slice(-50);
      setHistory(trimmedHistory);
      setHistoryIndex(trimmedHistory.length - 1);
    }
  }, [history, historyIndex]);

  // 撤销
  const undo = useCallback(() => {
    if (historyIndex > 0) {
      const prevState = history[historyIndex - 1];
      if (prevState) {
        setNodes(prevState.nodes);
        setEdges(prevState.edges);
        setHistoryIndex(historyIndex - 1);
        message.success('已撤销');
      }
    }
  }, [history, historyIndex, setNodes, setEdges]);

  // 重做
  const redo = useCallback(() => {
    if (historyIndex < history.length - 1) {
      const nextState = history[historyIndex + 1];
      if (nextState) {
        setNodes(nextState.nodes);
        setEdges(nextState.edges);
        setHistoryIndex(historyIndex + 1);
        message.success('已重做');
      }
    }
  }, [history, historyIndex, setNodes, setEdges]);

  // 键盘快捷键
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.ctrlKey || event.metaKey) {
        switch (event.key) {
          case 'z':
            if (event.shiftKey) {
              event.preventDefault();
              redo();
            } else {
              event.preventDefault();
              undo();
            }
            break;
          case 'y':
            event.preventDefault();
            redo();
            break;
          case 'a':
            event.preventDefault();
            // 全选节点
            setSelectedNodes(nodes);
            break;
          case 's':
            event.preventDefault();
            exportFlowChart();
            break;
          case 'c':
            if (selectedNodes.length > 0) {
              event.preventDefault();
              copySelectedNodes();
            }
            break;
        }
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [undo, redo, nodes, selectedNodes]);

  // 复制选中的节点
  const copySelectedNodes = useCallback(() => {
    if (selectedNodes.length === 0) {
      message.warning('请先选择要复制的节点');
      return;
    }

    const copiedNodes = selectedNodes.map(node => ({
      ...node,
      id: `${node.id}_copy_${Date.now()}`,
      position: {
        x: node.position.x + 50,
        y: node.position.y + 50
      }
    }));

    const newNodes = [...nodes, ...copiedNodes];
    setNodes(newNodes);
    saveToHistory(newNodes, edges);
    message.success(`已复制 ${selectedNodes.length} 个节点`);
  }, [selectedNodes, nodes, edges, setNodes, saveToHistory]);

  // 处理节点变化
  const onNodesChange = useCallback(
    (changes: NodeChange[]) => {
      const newNodes = applyNodeChanges(changes, nodes);
      setNodes(newNodes);
      
      // 只在节点位置改变完成时保存历史
      const hasPositionChange = changes.some(change => 
        change.type === 'position' && change.dragging === false
      );
      if (hasPositionChange) {
        saveToHistory(newNodes, edges);
      }
    },
    [nodes, edges, setNodes, saveToHistory]
  );

  // 处理边缘变化
  const onEdgesChange = useCallback(
    (changes: EdgeChange[]) => setEdges((eds) => applyEdgeChanges(changes, eds)),
    [setEdges]
  );

  // 处理连接
  const onConnect = useCallback(
    (params: Connection) => {
      const newEdges = addEdge({...params, animated: true, style: { stroke: '#1890ff', strokeWidth: 2 }}, edges);
      setEdges(newEdges);
      saveToHistory(nodes, newEdges);
    },
    [edges, nodes, setEdges, saveToHistory]
  );

  // 处理选择变化
  const onSelectionChange = useCallback(
    ({ nodes: selectedNodes }: { nodes: Node[], edges: Edge[] }) => {
      setSelectedNodes(selectedNodes);
    },
    []
  );

  // 双击节点编辑
  const onNodeDoubleClick = useCallback(
    (_event: React.MouseEvent, node: Node) => {
      setEditingNode(node);
      form.setFieldsValue({
        label: node.data.label,
        description: node.data.description || '',
        color: node.data.color || '#333',
        fontSize: node.data.fontSize || 14,
        backgroundColor: node.data.backgroundColor || '#fff',
        borderColor: node.data.borderColor || '#ccc',
        borderWidth: node.data.borderWidth || 1
      });
      setIsEditModalVisible(true);
    },
    [form]
  );

  // 添加节点
  const addNode = (type: NodeType) => {
    // 生成随机位置，避免节点重叠
    const position = { 
      x: Math.random() * 300 + 50, 
      y: Math.random() * 300 + 50 
    };

    const newNode: Node = {
      id: `node_${Date.now()}`,
      type: 'custom',
      position: position,
      data: { 
        label: getNodeLabel(type),
        description: '',
        backgroundColor: getNodeColor(type),
        color: '#fff',
        fontSize: 14,
        borderWidth: 2,
        borderColor: getNodeBorderColor(type)
      }
    };

    const newNodes = [...nodes, newNode];
    setNodes(newNodes);
    saveToHistory(newNodes, edges);
    setSelectedNodeType(null);
    message.success('节点已添加');
  };

  // 从模板添加节点
  const addNodeFromTemplate = (template: { label: string; data: Partial<NodeData> }) => {
    const position = { 
      x: Math.random() * 300 + 50, 
      y: Math.random() * 300 + 50 
    };

    const newNode: Node = {
      id: `node_${Date.now()}`,
      type: 'custom',
      position: position,
      data: { 
        label: template.label,
        description: template.data.description || '',
        backgroundColor: template.data.backgroundColor || '#1890ff',
        color: template.data.color || '#fff',
        fontSize: template.data.fontSize || 14,
        borderWidth: template.data.borderWidth || 2,
        borderColor: template.data.borderColor || '#0958d9'
      }
    };

    const newNodes = [...nodes, newNode];
    setNodes(newNodes);
    saveToHistory(newNodes, edges);
    message.success('模板节点已添加');
  };

  // 节点模板
  const nodeTemplates = [
    {
      key: 'decision',
      label: '决策节点',
      data: {
        description: '条件判断',
        backgroundColor: '#faad14',
        borderColor: '#d48806'
      }
    },
    {
      key: 'database',
      label: '数据库操作',
      data: {
        description: '数据存储/检索',
        backgroundColor: '#722ed1',
        borderColor: '#531dab'
      }
    },
    {
      key: 'api',
      label: 'API调用',
      data: {
        description: '外部接口调用',
        backgroundColor: '#13c2c2',
        borderColor: '#08979c'
      }
    },
    {
      key: 'user',
      label: '用户操作',
      data: {
        description: '用户交互环节',
        backgroundColor: '#eb2f96',
        borderColor: '#c41d7f'
      }
    }
  ];

  // 自动布局
  const autoLayout = () => {
    if (nodes.length === 0) {
      message.warning('暂无节点可布局');
      return;
    }

    const layoutedNodes = nodes.map((node, index) => {
      const row = Math.floor(index / 4);
      const col = index % 4;
      return {
        ...node,
        position: {
          x: col * 200 + 100,
          y: row * 150 + 100
        }
      };
    });

    setNodes(layoutedNodes);
    saveToHistory(layoutedNodes, edges);
    message.success('已自动布局');
  };

  // 导入流程图
  const importFlowChart = (file: File) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const content = e.target?.result as string;
        const data = JSON.parse(content);
        
        if (data.nodes && data.edges) {
          setNodes(data.nodes);
          setEdges(data.edges);
          saveToHistory(data.nodes, data.edges);
          message.success('流程图已导入');
        } else {
          message.error('文件格式不正确');
        }
      } catch (error) {
        message.error('文件解析失败');
      }
    };
    reader.readAsText(file);
  };

  // 获取节点标签
  const getNodeLabel = (type: NodeType): string => {
    switch (type) {
      case 'input': return '开始节点';
      case 'output': return '结束节点';
      default: return '处理节点';
    }
  };

  // 获取节点颜色
  const getNodeColor = (type: NodeType): string => {
    switch (type) {
      case 'input': return '#52c41a';
      case 'output': return '#ff4d4f';
      default: return '#1890ff';
    }
  };

  // 获取节点边框颜色
  const getNodeBorderColor = (type: NodeType): string => {
    switch (type) {
      case 'input': return '#389e0d';
      case 'output': return '#cf1322';
      default: return '#0958d9';
    }
  };

  // 删除选中的节点
  const deleteSelectedNodes = () => {
    if (selectedNodes.length === 0) {
      message.warning('请先选择要删除的节点');
      return;
    }

    const nodeIds = selectedNodes.map(node => node.id);
    const newNodes = nodes.filter((node) => !nodeIds.includes(node.id));
    const newEdges = edges.filter((edge) => 
      !nodeIds.includes(edge.source) && !nodeIds.includes(edge.target)
    );
    
    setNodes(newNodes);
    setEdges(newEdges);
    saveToHistory(newNodes, newEdges);
    message.success(`已删除 ${selectedNodes.length} 个节点`);
  };

  // 清空画布
  const clearCanvas = () => {
    Modal.confirm({
      title: '确认清空',
      content: '确定要清空整个画布吗？此操作无法撤销。',
      onOk: () => {
        setNodes([]);
        setEdges([]);
        saveToHistory([], []);
        message.success('画布已清空');
      }
    });
  };

  // 保存编辑
  const handleEditSave = () => {
    form.validateFields().then(values => {
      if (editingNode) {
        const newNodes = nodes.map((node) => {
          if (node.id === editingNode.id) {
            return {
              ...node,
              data: {
                ...node.data,
                ...values
              }
            };
          }
          return node;
        });
        
        setNodes(newNodes);
        saveToHistory(newNodes, edges);
        setIsEditModalVisible(false);
        setEditingNode(null);
        form.resetFields();
        message.success('节点已更新');
      }
    });
  };

  // 批量编辑选中节点的属性
  const handlePropertiesSave = () => {
    propertiesForm.validateFields().then(values => {
      if (selectedNodes.length > 0) {
        const newNodes = nodes.map((node) => {
          if (selectedNodes.some(selectedNode => selectedNode.id === node.id)) {
            return {
              ...node,
              data: {
                ...node.data,
                ...values
              }
            };
          }
          return node;
        });
        
        setNodes(newNodes);
        saveToHistory(newNodes, edges);
        setIsPropertiesDrawerVisible(false);
        propertiesForm.resetFields();
        message.success(`已更新 ${selectedNodes.length} 个节点`);
      }
    });
  };

  // 导出流程图数据
  const exportFlowChart = () => {
    const data = {
      nodes,
      edges,
      timestamp: new Date().toISOString()
    };
    
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `flowchart_${Date.now()}.json`;
    a.click();
    URL.revokeObjectURL(url);
    message.success('流程图已导出');
  };

  // 打开属性面板
  const openPropertiesPanel = () => {
    if (selectedNodes.length === 0) {
      message.warning('请先选择节点');
      return;
    }
    
    // 如果只选中一个节点，用该节点的属性填充表单
    if (selectedNodes.length === 1) {
      const node = selectedNodes[0];
      if (node) {
        propertiesForm.setFieldsValue({
          color: node.data.color || '#333',
          fontSize: node.data.fontSize || 14,
          backgroundColor: node.data.backgroundColor || '#fff',
          borderColor: node.data.borderColor || '#ccc',
          borderWidth: node.data.borderWidth || 1
        });
      }
    }
    
    setIsPropertiesDrawerVisible(true);
  };

  return (
    <div className="flowchart-container">
      <Card 
        title="流程图编辑器" 
        className="flowchart-card"
        extra={
          <Space>
            <Button 
              icon={<EditOutlined />}
              onClick={openPropertiesPanel}
              disabled={selectedNodes.length === 0}
            >
              属性面板
            </Button>
            <Button 
              type="primary" 
              icon={<SaveOutlined />}
              onClick={exportFlowChart}
            >
              导出
            </Button>
          </Space>
        }
      >
        {/* 工具栏 */}
        <div className="toolbar">
          <Space wrap>
            {/* 撤销重做 */}
            <Button.Group>
              <Tooltip title="撤销 (Ctrl+Z)">
                <Button
                  icon={<UndoOutlined />}
                  onClick={undo}
                  disabled={historyIndex <= 0}
                >
                  撤销
                </Button>
              </Tooltip>
              <Tooltip title="重做 (Ctrl+Y)">
                <Button
                  icon={<RedoOutlined />}
                  onClick={redo}
                  disabled={historyIndex >= history.length - 1}
                >
                  重做
                </Button>
              </Tooltip>
            </Button.Group>

            {/* 基本节点 */}
            <Button
              type={selectedNodeType === 'input' ? 'primary' : 'default'}
              onClick={() => addNode('input')}
              style={{ backgroundColor: selectedNodeType === 'input' ? undefined : '#52c41a', 
                       color: selectedNodeType === 'input' ? undefined : 'white' }}
            >
              开始节点
            </Button>
            <Button
              type={selectedNodeType === 'default' ? 'primary' : 'default'}
              onClick={() => addNode('default')}
              style={{ backgroundColor: selectedNodeType === 'default' ? undefined : '#1890ff', 
                       color: selectedNodeType === 'default' ? undefined : 'white' }}
            >
              处理节点
            </Button>
            <Button
              type={selectedNodeType === 'output' ? 'primary' : 'default'}
              onClick={() => addNode('output')}
              style={{ backgroundColor: selectedNodeType === 'output' ? undefined : '#ff4d4f', 
                       color: selectedNodeType === 'output' ? undefined : 'white' }}
            >
              结束节点
            </Button>

            {/* 模板节点 */}
            <Dropdown
              menu={{
                items: nodeTemplates.map(template => ({
                  key: template.key,
                  label: template.label,
                  onClick: () => addNodeFromTemplate(template)
                }))
              }}
            >
              <Button icon={<AppstoreOutlined />}>
                模板节点
              </Button>
            </Dropdown>

            {/* 操作按钮 */}
            <Tooltip title="复制选中节点 (Ctrl+C)">
              <Button 
                icon={<CopyOutlined />} 
                onClick={copySelectedNodes}
                disabled={selectedNodes.length === 0}
              >
                复制 {selectedNodes.length > 0 && `(${selectedNodes.length})`}
              </Button>
            </Tooltip>
            
            <Button 
              icon={<DeleteOutlined />} 
              onClick={deleteSelectedNodes}
              danger
              disabled={selectedNodes.length === 0}
            >
              删除节点 {selectedNodes.length > 0 && `(${selectedNodes.length})`}
            </Button>
            
            <Button 
              icon={<ClearOutlined />}
              onClick={clearCanvas}
            >
              清空画布
            </Button>

            {/* 布局和设置 */}
            <Button 
              icon={<SettingOutlined />}
              onClick={autoLayout}
              disabled={nodes.length === 0}
            >
              自动布局
            </Button>

            {/* 导入导出 */}
            <Upload
              accept=".json"
              showUploadList={false}
              beforeUpload={(file) => {
                importFlowChart(file);
                return false;
              }}
            >
              <Button icon={<UploadOutlined />}>
                导入
              </Button>
            </Upload>

            {/* 网格对齐设置 */}
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <Switch
                checked={isSnapToGrid}
                onChange={setIsSnapToGrid}
                size="small"
              />
              <span style={{ fontSize: '12px' }}>网格对齐</span>
            </div>
          </Space>
        </div>

        {/* 画布 - 使用ReactFlow */}
        <div className="canvas-container" style={{ height: 600 }}>
          <ReactFlow
            nodes={nodes}
            edges={edges}
            nodeTypes={nodeTypes}
            onNodesChange={onNodesChange}
            onEdgesChange={onEdgesChange}
            onConnect={onConnect}
            onNodeDoubleClick={onNodeDoubleClick}
            onSelectionChange={onSelectionChange}
            fitView
            snapToGrid={isSnapToGrid}
            snapGrid={[gridSize, gridSize]}
            multiSelectionKeyCode="Shift"
            deleteKeyCode="Delete"
            defaultViewport={{ x: 0, y: 0, zoom: 1 }}
            minZoom={0.1}
            maxZoom={2}
            attributionPosition="bottom-left"
          >
            <Background color="#f0f0f0" gap={gridSize} />
            <Controls showZoom showFitView showInteractive />
            <MiniMap 
              nodeStrokeColor={(n) => n.data.borderColor || '#ccc'}
              nodeColor={(n) => n.data.backgroundColor || '#fff'}
              nodeBorderRadius={2}
              pannable
              zoomable
            />
          </ReactFlow>
        </div>

        {/* 说明 */}
        <div className="instructions">
          <p><strong>使用说明：</strong></p>
          <ul>
            <li>1. 点击上方的节点按钮添加不同类型的节点，或使用<strong>模板节点</strong>快速添加</li>
            <li>2. 拖拽节点可以移动位置，支持<strong>网格对齐</strong>功能</li>
            <li>3. <strong>连线功能：</strong>拖拽节点四侧的<strong>蓝色小圆点</strong>可以创建连线（上下左右四个方向）</li>
            <li>4. <strong>双击节点可以编辑节点内容和样式</strong></li>
            <li>5. 按住Shift可以多选节点，使用属性面板批量编辑</li>
            <li>6. 支持<strong>撤销重做</strong> (Ctrl+Z/Y)、<strong>复制</strong> (Ctrl+C)、<strong>全选</strong> (Ctrl+A)</li>
            <li>7. <strong>自动布局</strong>功能可以整理节点排列</li>
            <li>8. 可以<strong>导入/导出</strong>JSON文件保存流程图</li>
            <li>9. 选中节点或连线后按Delete键即可删除</li>
            <li>10. 右下角提供缩放、居中等操作，左下角的小地图可快速导航</li>
          </ul>
          <div style={{ marginTop: '12px', padding: '8px', backgroundColor: '#e6f7ff', border: '1px solid #91d5ff', borderRadius: '4px' }}>
            <strong>连线操作提示：</strong>
            鼠标悬停在节点上时，会显示四个蓝色连接点。拖拽连接点到另一个节点的连接点，即可建立连线。
          </div>
        </div>
      </Card>

      {/* 节点编辑弹窗 */}
      <Modal
        title="编辑节点"
        open={isEditModalVisible}
        onOk={handleEditSave}
        onCancel={() => {
          setIsEditModalVisible(false);
          setEditingNode(null);
          form.resetFields();
        }}
        okText="保存"
        cancelText="取消"
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            color: '#333',
            fontSize: 14,
            backgroundColor: '#fff',
            borderColor: '#ccc',
            borderWidth: 1
          }}
        >
          <Form.Item
            label="节点标题"
            name="label"
            rules={[{ required: true, message: '请输入节点标题' }]}
          >
            <Input placeholder="请输入节点标题" />
          </Form.Item>
          
          <Form.Item
            label="节点描述"
            name="description"
          >
            <Input.TextArea rows={3} placeholder="请输入节点描述（可选）" />
          </Form.Item>
          
          <div style={{ display: 'flex', gap: '16px' }}>
            <Form.Item
              label="文字颜色"
              name="color"
              style={{ flex: 1 }}
            >
              <ColorPicker showText />
            </Form.Item>
            
            <Form.Item
              label="字体大小"
              name="fontSize"
              style={{ flex: 1 }}
            >
              <InputNumber min={10} max={24} addonAfter="px" />
            </Form.Item>
          </div>
          
          <div style={{ display: 'flex', gap: '16px' }}>
            <Form.Item
              label="背景颜色"
              name="backgroundColor"
              style={{ flex: 1 }}
            >
              <ColorPicker showText />
            </Form.Item>
            
            <Form.Item
              label="边框颜色"
              name="borderColor"
              style={{ flex: 1 }}
            >
              <ColorPicker showText />
            </Form.Item>
          </div>
          
          <Form.Item
            label="边框宽度"
            name="borderWidth"
          >
            <InputNumber min={0} max={5} addonAfter="px" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 属性面板抽屉 */}
      <Drawer
        title={`批量编辑属性 (${selectedNodes.length}个节点)`}
        placement="right"
        onClose={() => setIsPropertiesDrawerVisible(false)}
        open={isPropertiesDrawerVisible}
        width={400}
        extra={
          <Button type="primary" onClick={handlePropertiesSave}>
            应用更改
          </Button>
        }
      >
        <Form
          form={propertiesForm}
          layout="vertical"
          initialValues={{
            color: '#333',
            fontSize: 14,
            backgroundColor: '#fff',
            borderColor: '#ccc',
            borderWidth: 1
          }}
        >
          <Form.Item
            label="文字颜色"
            name="color"
          >
            <ColorPicker showText />
          </Form.Item>
          
          <Form.Item
            label="字体大小"
            name="fontSize"
          >
            <InputNumber min={10} max={24} addonAfter="px" style={{ width: '100%' }} />
          </Form.Item>
          
          <Form.Item
            label="背景颜色"
            name="backgroundColor"
          >
            <ColorPicker showText />
          </Form.Item>
          
          <Form.Item
            label="边框颜色"
            name="borderColor"
          >
            <ColorPicker showText />
          </Form.Item>
          
          <Form.Item
            label="边框宽度"
            name="borderWidth"
          >
            <InputNumber min={0} max={5} addonAfter="px" style={{ width: '100%' }} />
          </Form.Item>
        </Form>
        
        <div style={{ marginTop: '20px', padding: '16px', backgroundColor: '#f5f5f5', borderRadius: '6px' }}>
          <h4>选中的节点:</h4>
          {selectedNodes.map(node => (
            <div key={node.id} style={{ marginBottom: '8px', padding: '8px', backgroundColor: '#fff', borderRadius: '4px' }}>
              <strong>{node.data.label}</strong>
              <br />
              <span style={{ fontSize: '12px', color: '#666' }}>ID: {node.id}</span>
            </div>
          ))}
        </div>
      </Drawer>
    </div>
  );
};

export default FlowChart;